package com.hengpeng.msls.service.invest.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.Restrictions;
import com.hengpeng.common.persist.query.constants.QueryConstants.JoinType;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.itfinbase.persist.InvestInfo.InvestStatus;
import com.hengpeng.itfinbase.persist.ReceivePlan;
import com.hengpeng.msls.service.ServiceFactory;
import com.hengpeng.msls.service.invest.InvestInfoService;
import com.hengpeng.msls.vo.invest.InvestInfoVo;

@Lazy
@Service
public class InvestInfoServiceImpl implements InvestInfoService
{
	@Autowired
	private ServiceFactory serviceFactory;

	@Override
	public List<InvestInfo> queryInvestList(Long borrowId, Long investUserId, InvestInfo.InvestStatus status)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		if (borrowId != null)
		{
			query.eq("borrowInfoId", borrowId);
		}
		if (investUserId != null)
		{
			query.eq("investUserId", investUserId);
		}
		if (status != null)
		{
			query.eq("status", status);
		}
		query.setQueryType(QueryType.JDBC);
		return serviceFactory.getProtFactory().queryList(query, InvestInfo.class);
	}

	@Override
	public List<InvestInfo> queryAccountInvestList(Long investUserId, String status, String queryTime)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		if (investUserId != null)
		{
			query.eq("investUserId", investUserId);
		}
		if ("SUCCESS".equals(status))
		{
			query.inArray("status", new InvestStatus[] { InvestStatus.SUCESS, InvestStatus.LOANED,
					InvestStatus.LOANING, InvestStatus.RETURNED });
		}
		else if ("DEALING".equals(status))
		{
			query.inArray("status", new InvestStatus[] { InvestStatus.INVESTING });
		}
		else if ("FAIL".equals(status))
		{
			query.inArray("status", new InvestStatus[] { InvestStatus.FAILURE, InvestStatus.CANCLING,
					InvestStatus.CANCLED });
		}
		if ("three_day".equals(queryTime))
		{// 查询三天以内的记录
			query.ge("investTime", DateTimeUtil.addDate(new Date(), -3));
		}
		else if ("one_week".equals(queryTime))
		{// 查询一周以内的记录
			query.ge("investTime", DateTimeUtil.addDate(new Date(), -7));
		}
		else if ("one_month".equals(queryTime))
		{// 查询一个月之内的记录
			query.ge("investTime", DateTimeUtil.addDate(new Date(), -30));
		}
		else if ("three_month".equals(queryTime))
		{// 查询三个月之内的记录
			query.ge("investTime", DateTimeUtil.addDate(new Date(), -90));
		}
		else
		{// 默认显示一周的记录
			query.ge("investTime", DateTimeUtil.addDate(new Date(), -7));
		}
		query.desc("investTime");
		query.setQueryType(QueryType.JDBC);
		// System.out.println(query.getSqlResult().getSql());
		return serviceFactory.getProtFactory().queryList(query, InvestInfo.class);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public ServiceResult<List<InvestInfoVo>> queryMyInvestList(Long investUserId, InvestStatus status,
			String arrivalTime, Integer curPage, Integer pageSize)
	{
		/**
		 * select t.borrowName,t.borrowRate,t.investTime,t.investMoney,t.status, sum(case r.status when 'WAITREC' then
		 * r.recBaseMoney else 0 end), sum(case r.status when 'WAITREC' then r.recInterestMoney else 0 end), sum(case
		 * r.status when 'RECEIVED' then r.recBaseMoney else 0 end), sum(case r.status when 'RECEIVED' then
		 * r.recInterestMoney else 0 end), t.investUserId,t.borrowInfoId,t.rewardRate,t.borrowMoney,t.raiseMoney ,t.id
		 * from ( select i.id,b.borrowName,b.borrowRate,i.investTime,i.investMoney,i.status,
		 * i.investUserId,i.borrowInfoId,b.rewardRate,b.borrowMoney,b.raiseMoney from InvestInfo i inner join BorrowInfo
		 * b on i.borrowInfoId = b.id where i.status = 'SUCESS' and i.investUserId = 143702395752801248 ) t left join
		 * ReceivePlan r on t.id = r.investmentInfoId group by
		 * t.id,t.borrowName,t.borrowRate,t.investTime,t.investMoney,t.status,t.investUserId,
		 * t.borrowInfoId,t.rewardRate,t.borrowMoney,t.raiseMoney
		 */
		List<InvestInfoVo> dataList = new ArrayList<InvestInfoVo>();
		DynamicQuery queryinner = new DynamicQuery(InvestInfo.class, "i");
		queryinner.createAlias(BorrowInfo.class, JoinType.INNERJOIN, "b");
		queryinner.eqProperty("i.borrowInfoId", "b.id");
		queryinner.addProjection(Projections.property("i.id"));//
		queryinner.addProjection(Projections.property("b.borrowName"));//
		queryinner.addProjection(Projections.property("b.borrowRate"));//
		queryinner.addProjection(Projections.property("i.investTime"));//
		queryinner.addProjection(Projections.property("i.investMoney"));//
		queryinner.addProjection(Projections.property("i.status"));//
		queryinner.addProjection(Projections.property("i.investUserId"));//
		queryinner.addProjection(Projections.property("i.borrowInfoId"));//
		queryinner.addProjection(Projections.property("b.rewardRate"));//
		queryinner.addProjection(Projections.property("b.borrowMoney"));//
		queryinner.addProjection(Projections.property("b.raiseMoney"));//
		if (status != null)
		{
			queryinner.eq("i.status", status);
		}
		else
		{// 默认显示回款中
			queryinner.eq("i.status", InvestStatus.LOANED);
		}
		queryinner.eq("i.investUserId", investUserId);

		DynamicQuery queryout = new DynamicQuery(queryinner, "t");
		queryout.createAlias(ReceivePlan.class, JoinType.LEFTJOIN, "r");
		queryout.on(Restrictions.eqProperty("t.id", "r.investmentInfoId"));
		queryout.addProjection(Projections.property("t.borrowName"));// 0
		queryout.addProjection(Projections.property("t.borrowRate"));// 1
		queryout.addProjection(Projections.property("t.investTime"));// 2
		queryout.addProjection(Projections.property("t.investMoney"));// 3
		queryout.addProjection(Projections.property("t.status"));// 4
		queryout.addProjection(Projections.property("sum(case r.status when 'WAITREC' then r.recBaseMoney else 0 end)"));// 5待收本金
		queryout.addProjection(Projections
				.property("sum(case r.status when 'WAITREC' then r.recInterestMoney + r.recAddMoney else 0 end)"));// 6待收利息
		queryout.addProjection(Projections
				.property("sum(case r.status when 'RECEIVED' then r.recBaseMoney else 0 end)"));// 7已收本金
		queryout.addProjection(Projections
				.property("sum(case r.status when 'RECEIVED' then r.recInterestMoney + r.recAddMoney else 0 end)"));// 8已收利息
		queryout.addProjection(Projections.property("t.investUserId"));// 9
		queryout.addProjection(Projections.property("t.borrowInfoId"));// 10
		queryout.addProjection(Projections.property("t.rewardRate"));// 11
		queryout.addProjection(Projections.property("t.borrowMoney"));// 12
		queryout.addProjection(Projections.property("t.raiseMoney"));// 13
		queryout.addProjection(Projections.property("t.id"));// 14

		if (!StringHelper.isEmpty(arrivalTime))
		{
			queryout.eq("date_format(r.arrivalTime,'%Y-%m-%d')", arrivalTime);
		}

		queryout.addGourp("t.borrowName");
		queryout.addGourp("t.borrowRate");
		queryout.addGourp("t.investTime");
		queryout.addGourp("t.investMoney");
		queryout.addGourp("t.status");
		queryout.addGourp("t.investUserId");
		queryout.addGourp("t.borrowInfoId");
		queryout.addGourp("t.rewardRate");
		queryout.addGourp("t.borrowMoney");
		queryout.addGourp("t.raiseMoney");
		queryout.addGourp("t.id");

		DynamicQuery queryTotal = new DynamicQuery(queryout, "total");
		queryTotal.setPageIndex(curPage);
		queryTotal.setPageSize(pageSize);
		queryTotal.setIsSearchTotalCount(true);
		queryTotal.setQueryType(QueryType.JDBC);

		QueryResult result = serviceFactory.getProtFactory().remoteQuery(queryTotal, null);
		Long count = result.getTotalCount();
		ServiceResult<List<InvestInfoVo>> serviceResult = new ServiceResult<List<InvestInfoVo>>();// 设置返回值

		if (result.getResults() != null && result.getResults().size() > 0)
		{
			for (int i = 0; i < result.getResults().size(); i++)
			{
				Object[] obj = (Object[]) result.getResults().get(i);
				InvestInfoVo vo = new InvestInfoVo();
				vo.setBorrowName(String.valueOf(obj[0]));
				vo.setBorrowRate(String.valueOf(obj[1]));
				vo.setInvestTime(DateTimeUtil.formatToDate(String.valueOf(obj[2]), DateTimeUtil.DATE_FORMAT_YMD));
				vo.setInvestMoney(Long.parseLong(String.valueOf(obj[3])));
				vo.setStatus(InvestInfo.InvestStatus.valueOf(String.valueOf(obj[4])));
				vo.setUnReceiveBaseMoney(Long.parseLong(String.valueOf(obj[5])));// 待收本金
				vo.setUnReceiveInterestMoney(Long.parseLong(String.valueOf(obj[6])));// 待收利息
				vo.setReceivedBaseMoney(Long.parseLong(String.valueOf(obj[7])));// 已收本金
				vo.setReceivedInterestMoney(Long.parseLong(String.valueOf(obj[8])));// 已收利息
				vo.setInvestUserId(Long.parseLong(String.valueOf(obj[9])));
				vo.setBorrowInfoId(Long.parseLong(String.valueOf(obj[10])));
				vo.setRewardRate(String.valueOf(obj[11]));
				Double borrowMoney = Double.parseDouble(String.valueOf(obj[12]));
				Double raiseMoney = Double.parseDouble(String.valueOf(obj[13]));
				vo.setRaiseProgress(Math.floor(raiseMoney / borrowMoney * 100));
				dataList.add(vo);
			}
		}
		serviceResult.setReturnValue(dataList);
		serviceResult.setReturnListSize(count.intValue());

		return serviceResult;
	}
}
